<template>
  <div class="clearfix header" :class="$style['header']">
    <div class="wrapper">
      <img src="@/assets/img/logo.png" alt="" :class="$style['logo']" />
      <el-button type="primary" v-if="!isLogin" :class="$style['login']" size="mini" @click="showLoginPop"
        >登录</el-button
      >
      <div :class="$style['user']" v-else>
        <el-dropdown>
          <span>
            <span :class="$style['user-name']"> {{ userInfo.nickname }}</span>
            <span :class="$style['dropdown']">
              <img
                :src="userInfo.avatar ? userInfo.avatar : defaultImg"
                alt=""
                :onerror="`onerror=null;src='${defaultImg}'`"
              />
            </span>
          </span>

          <template #dropdown>
            <el-dropdown-menu :class="$style['dropdown-menu']">
              <el-dropdown-item command="a"><router-link to="/user/create">创作平台</router-link></el-dropdown-item>
              <el-dropdown-item command="a"><router-link to="/user/course">我的课程</router-link></el-dropdown-item>
              <el-dropdown-item command="a"><router-link to="/user/question">我的题库</router-link></el-dropdown-item>
              <el-dropdown-item command="a"><router-link to="/user/exam">我的考试</router-link></el-dropdown-item>
              <el-dropdown-item command="a"><router-link to="/user">个人中心</router-link></el-dropdown-item>
              <el-dropdown-item command="b" @click="loginOut"><span>退出</span></el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <router-link to="/message" :class="$style['msg-link']">
          <svg-icon icon-class="iconmessage" :class="$style['message-ico']"></svg-icon>
          <span :class="$style['dot']" v-if="unreadMsg.totalMsgNum > 0">{{
            unreadMsg.totalMsgNum > 99 ? '99+' : unreadMsg.totalMsgNum
          }}</span>
        </router-link>
      </div>
      <el-menu
        :default-active="activeIndex"
        :class="$style['el-menu-demo']"
        mode="horizontal"
        text-color="#333"
        active-text-color="#3f5ac1"
        :router="true"
      >
        <el-menu-item index="/">首页</el-menu-item>
        <el-menu-item index="/news">资讯</el-menu-item>
        <el-menu-item index="/course">课程</el-menu-item>
        <el-menu-item index="/questionbank">题库</el-menu-item>
        <el-menu-item index="/exam">考试</el-menu-item>
        <el-menu-item index="/about">关于</el-menu-item>
      </el-menu>
    </div>
  </div>
  <el-dialog
    title="登录"
    v-model="loginVisible"
    width="500px"
    :before-close="handleClose"
    center
    custom-class="login-pop"
  >
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <el-form-item label="用户名：" :label-width="formLabelWidth" class="form-item" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" size="medium" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码：" :label-width="formLabelWidth" class="form-item" prop="password">
        <el-input
          v-model="ruleForm.password"
          autocomplete="off"
          size="medium"
          placeholder="请输入密码"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码：" :label-width="formLabelWidth" class="code-item form-item" prop="captcha">
        <el-input
          v-model="ruleForm.captcha"
          autocomplete="off"
          size="medium"
          @keydown.enter="submitForm('ruleForm')"
        ></el-input>
        <img :src="rangeImg" alt="" @click="getRandomImage" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">登 录</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import defaultImg from '@/assets/img/user.png';
export default {
  data() {
    return {
      // 当前页面路径
      activeIndex: '/',

      // 表单数据
      ruleForm: {
        username: '',
        password: '',
        captcha: '',
      },
      // 表单规则
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      },
      // 登录label宽度
      formLabelWidth: '100px',
      // 获取验证码时间搓
      parseDate: '',
      // 验证码
      rangeImg: '',
      // 是否登录
      isLogin: !!localStorage.getItem('token'),
      // 用户数据
      userInfo: JSON.parse(localStorage.getItem('userInfo')),
      // 默认头像
      defaultImg: defaultImg,
    };
  },
  computed: {
    // 登录弹窗
    loginVisible() {
      return this.$store.state.loginVisible;
    },
    // 用户消息未读数
    unreadMsg() {
      return this.$store.state.unreadMsg;
    },
  },
  watch: {
    $route: function() {
      const pathData = this.$route.path.split('/');
      const activePath =  pathData.length >= 2 ? `/${pathData[1]}`: '/';
      this.activeIndex = activePath;
    },
    loginVisible: function() {
      if (this.loginVisible) {
        this.getRandomImage();
      }
    },
  },
  mounted() {
    if (this.isLogin) {
      this.getMsgDatas();
    }
  },
  methods: {
    // 获取未读消息数
    getMsgDatas() {
      this.$store.dispatch('getReadData', { that: this });
    },
    // 获取登录验证码
    getRandomImage() {
      const timestamp = Date.parse(new Date());
      this.parseDate = timestamp;
      const that = this;
      this.$request
        .get(`/studyStudent/randomImage/${timestamp}`)
        .then(function(response) {
          const { data = {} } = response || {};
          that.rangeImg = data.data || '';
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 提交登录表单
    submitForm(formName) {
      const that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$request
            .post(`/studyStudent/login`, { ...this.ruleForm, checkKey: this.parseDate })
            .then(function(response) {
              const { data = {} } = response || {};
              if (data.code === 0) {
                const { data = {} } = response.data || {};
                const { userInfo = {} } = data;
                localStorage.setItem('token', data.token);
                const userInfoData = {
                  avatar: userInfo.avatar, // 图片
                  nickname: userInfo.nickname, // 名字
                  sex: userInfo.sex, // 性别
                  id: userInfo.id, // id
                };
                localStorage.setItem('userInfo', JSON.stringify(userInfoData));
                that.$router.go(0);
                that.$store.commit('setLoginVisible', false);
              }
              if (data.msg === '验证码错误') {
                that.getRandomImage();
                that.ruleForm.captcha = '';
              }
            })
            .catch(function(error) {
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
    // 显示登录弹窗
    showLoginPop() {
      this.$store.commit('setLoginVisible', true);
    },
    // 关闭
    handleClose() {
      this.$store.commit('setLoginVisible', false);
    },
    // 退出
    loginOut() {
      const that = this;
      this.$request
        .post(`/studyStudent/logout`, {})
        .then(function(response) {
          localStorage.clear();
          that.$router.go(0);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
  },
};
</script>
<style lang="scss">
.header {
  .el-menu--horizontal > .el-menu-item {
    margin: 0 27px;
    padding: 0 10px;
    font-size: 16px;
  }
  .el-menu.el-menu--horizontal {
    float: right;
    border-bottom: none;
  }
}
.el-dialog.login-pop {
  border-radius: 10px;
  overflow: hidden;
  .el-dialog__headerbtn {
    .el-dialog__close {
      font-size: 24px;
      color: #fff;
      &:hover {
        opacity: 0.8;
      }
    }
  }
  .el-dialog__body {
    padding-bottom: 0;
  }
  .el-dialog__header {
    background-color: $color-primary;
    .el-dialog__title {
      color: #fff;
    }
  }
  .form-item {
    color: #fff;
    .el-input {
      width: 300px;
    }
  }
  .code-item {
    .el-input {
      width: 180px;
      vertical-align: middle;
    }
    img {
      display: inline-block;
      margin-left: 10px;
      height: 36px;
      width: 110px;
      vertical-align: middle;
    }
  }
}
</style>
<style lang="scss" module>
.header {
  position: relative;
  box-shadow: 0 2px 8px 0 rgba(27, 27, 98, 0.1);
  z-index: 9;
  background: #fff;
  .login {
    float: right;
    margin-top: 15px;
    margin-left: 100px;
    border-radius: 10px;
  }
}
.message-ico {
  display: inline-block;
  margin-top: 10px;
  margin-left: 20px;
  font-size: 20px;
  color: $text-grey;
  vertical-align: middle !important;
  cursor: pointer;
}
.logo {
  height: 60px;
  float: left;
  margin-top: 10px;
  width:177px;
  height:33px;
}
.user {
  float: right;
  margin-left: 100px;
  .dropdown {
    display: inline-block;
    margin-top: 10px;
    width: 40px;
    height: 40px;
    border-radius: 40px;
    overflow: hidden;
    vertical-align: middle;
    cursor: pointer;
  }
  .user-name {
    display: inline-block;
    margin-top: 10px;
    margin-right: 10px;
    line-height: 40px;
    vertical-align: middle;
    cursor: pointer;
  }
  img {
    width: 100%;
    height: 100%;
  }
}
.dropdown-menu {
  a,
  span {
    display: block;
    padding: 0 10px;
    color: #333;
    width: 100%;
    height: 100%;
    &:hover {
      color: $color-primary;
    }
  }
}
.msg-link {
  position: relative;
  .dot {
    position: absolute;
    top: -7px;
    right: -7px;
    height: 16px;
    line-height: 16px;
    border-radius: 10px;
    padding: 0 5px;
    background-color: red;
    color: #fff;
    font-size: 12px;
  }
}
</style>
